<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
	<th:block th:include="include/include :: header('修改用户头像')" />
	<th:block th:include="include/include :: cropbox-css" />
<style type="text/css">

</style>
</head>
<body class="white-bg">
    <div class="container"> 
        <div class="imageBox"> 
	        <div class="thumbBox"></div> 
	        <div class="spinner" style="display: none">Loading...</div> 
	   </div> 
	   <div class="action"> 
	       <div class="new-contentarea tc">
	           <a href="javascript:void(0)" class="upload-img"> <label for="avatar">上传图像</label> </a> 
	           <form enctype="multipart/form-data" id="formImg" method="post" action="">
	           		<input type="file" class="" name="avatar" id="avatar" accept="image/*"/>
	           </form>
	           
	       </div> 
	   <input type="button" id="btnCrop" class="Btnsty_peyton" value="裁切" /> 
	   <input type="button" id="btnZoomIn" class="Btnsty_peyton" value="+" /> 
	   <input type="button" id="btnZoomOut" class="Btnsty_peyton" value="-" /> 
	   </div> 
	   <div class="cropped"></div> 
   
    </div>
<th:block th:include="include/include :: footer" />
<th:block th:include="include/include :: cropbox-js" />
<script th:src="@{/js/jquery.form.min.js}"></script>
<script type="text/javascript">
var cropper;
var ieImgSrc
$(window).load(function() {
	console.log('parent',parent)
	var avatar = '[[${user.avatar}]]';
    var options = {
        thumbBox: '.thumbBox',
        spinner: '.spinner',
        imgSrc: $.common.isEmpty(avatar) ? ctx + 'img/user_w.jpeg' : ctx + avatar.substr(1)
    }
    cropper = $('.imageBox').cropbox(options);
    $('#avatar').on('change', function() {
    	if (IEVersion()){ //ie8 ie9
    		
    		this.select();
			top.parent.document.body.focus();
			ieImgSrc = document.selection.createRange().text;
			console.log('ooooooooo',document.selection.createRange())
  			$(".thumbBox").html('<div class="ie-img" style="width:100%;height:100%;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=scale,src=\'' + ieImgSrc + '\'"></div>')
			$('.spinner').css('display','none')
		
    
    	}else{
    		 var reader = new FileReader();
    	        reader.onload = function(e) {
    	            options.imgSrc = e.target.result;
    	            //根据MIME判断上传的文件是不是图片类型
    	            if((options.imgSrc).indexOf("image/")==-1){
    	                $.modal.alertWarning("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    	            } else {
    	                cropper = $('.imageBox').cropbox(options);
    	            }
    	        }
    	        reader.readAsDataURL(this.files[0]);
    	}
       
    })
    
	$('#btnCrop').on('click', function(){
		var img = cropper.getDataURL();
		$('.cropped').html('');
		$('.cropped').append('<img src="'+img+'" align="absmiddle" style="width:64px;margin-top:4px;border-radius:64px;box-shadow:0px 0px 12px #7E7E7E;" ><p>64px*64px</p>');
		$('.cropped').append('<img src="'+img+'" align="absmiddle" style="width:128px;margin-top:4px;border-radius:128px;box-shadow:0px 0px 12px #7E7E7E;"><p>128px*128px</p>');
		$('.cropped').append('<img src="'+img+'" align="absmiddle" style="width:180px;margin-top:4px;border-radius:180px;box-shadow:0px 0px 12px #7E7E7E;"><p>180px*180px</p>');
	})
	
	$('#btnZoomIn').on('click', function(){
		cropper.zoomIn();
	})
	
	$('#btnZoomOut').on('click', function(){
		cropper.zoomOut();
	})
	

	
});

function submitHandler() {
	if (IEVersion()) {
		 var img = ieBase64($('#avatar'))
		 var ajax_option={
			 	url: ctx + "admin/user/updateAvatar",
			 	secureuri: false,
		        type: "post",
		        fileElementId: 'avatar', //
                data: {},
		        dataType:"json",
		        success:function(result){
		        	$.operate.saveSuccess(result);
		            /* layer.closeAll("loading"); */
		        },
		        error:function(data){
		        	console.log('error',data)
		           /*  $('#btnupfile').removeAttr("disabled");
		            layer.closeAll("loading");
		            layer.alert("上传失败，请重新上传",{icon:2}); */
		        }
		    };
		 //$('#formImg').ajaxSubmit(ajax_option);
		 $.ajaxFileUpload(ajax_option)
	}else{
		var img = cropper.getBlob();
	    var formdata = new FormData();
	    formdata.append("avatarfile", img,getFileName($('#avatar').val()));
	    $.ajax({
	        url: ctx + "admin/user/updateAvatar",
	        data: formdata,
	        type: "post",
	        processData: false,
	        contentType: false,
	        success: function(result) {
	        	$.operate.saveSuccess(result);
	        	parent.parent.location.reload();
	        }
	    })
	    
	}
    
    
    
    
   
}
//获取文件名称
function getFileName(path) {

	var pos1 = path.lastIndexOf('/');

	var pos2 = path.lastIndexOf('\\');

	var pos = Math.max(pos1, pos2);

	if (pos < 0) return path

	return path.substring(pos + 1);
}

//判断ie浏览器版本 以ie10为分界，ie10以下返回true，否则返回false
function IEVersion() {
    //取得浏览器的userAgent字符串
    var userAgent = navigator.userAgent;
    //判断是否IE浏览器
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1;
    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion < 10) {
            return true;
        }
    } else {
        return false;
    }
}

function ieBase64(file){//file是input type="file" 对象dom
    var realPath, xmlHttp, xml_dom, tmpNode, imgData;
    realPath = file;//获取文件的真实本地路径.
    xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
    xmlHttp.open("POST",realPath, false);
    xmlHttp.send("");
    xml_dom = new ActiveXObject("MSXML2.DOMDocument");
    tmpNode = xml_dom.createElement("tmpNode");
    tmpNode.dataType = "bin.base64";
    tmpNode.nodeTypedValue = xmlHttp.responseBody;
    imgData = "data:image/"+ "bmp" +";base64," + tmpNode.text.replace(/\n/g,"");
    //计算文件大小
    var str=imgData.substring(22);
    var equalIndex= str.indexOf('=');
    if(str.indexOf('=')>0){
        str=str.substring(0, equalIndex);
    }
    var strLength=str.length;
    var fileLength=parseInt(strLength-(strLength/8)*2);
    if(fileLength > 5120000){//图片大于5M
      alert("图片不能大于5M");
      return;
    }
    //callback(imgData);
    return imgData;//渲染图片
}


</script>
</body>
</html>
